<template>
  <div class="lesson-form-page">
    <div class="page-header">
      <h1>{{ isEdit ? '编辑课程' : '创建课程' }}</h1>
      <div class="header-actions">
        <el-button @click="$router.back()">返回</el-button>
        <el-button type="primary" @click="handleSave" :loading="isSaving">
          保存
        </el-button>
      </div>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="lesson-form"
    >
      <el-card title="基本信息">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入课程标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程标识" prop="slug">
              <el-input v-model="form.slug" placeholder="请输入课程标识" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类">
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度级别" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="请选择难度">
                <el-option label="初级" value="beginner" />
                <el-option label="中级" value="intermediate" />
                <el-option label="高级" value="advanced" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="课程简介">
          <el-input
            v-model="form.excerpt"
            type="textarea"
            :rows="3"
            placeholder="请输入课程简介"
          />
        </el-form-item>
      </el-card>

      <el-card title="课程内容" class="content-card">
        <el-form-item label="课程内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="20"
            placeholder="请输入课程内容（支持 Markdown）"
          />
        </el-form-item>
      </el-card>

      <el-card title="封面图片">
        <el-form-item>
          <div class="cover-upload-section">
            <div class="upload-options">
              <ImageUpload
                v-model="form.coverImage"
                placeholder="点击上传封面图"
                hint="建议尺寸：800x450，支持 JPG、PNG、GIF、WebP 格式"
                width="300px"
                height="180px"
                alt="课程封面"
                @upload-success="handleCoverImageSuccess"
                @upload-error="handleCoverImageError"
                @remove="handleCoverImageRemove"
              />
              <div class="upload-divider">或</div>
              <el-button 
                type="primary" 
                plain 
                @click="showImageSelector = true"
                :icon="Picture"
              >
                从图库选择
              </el-button>
            </div>
            
            <!-- 当前封面预览 -->
            <div v-if="form.coverImage" class="current-cover-preview">
              <div class="preview-label">当前封面：</div>
              <div class="preview-image-wrapper">
                <img 
                  :src="getImagePreviewUrl(form.coverImage)" 
                  :alt="form.title || '课程封面'"
                  class="preview-image"
                  @error="handlePreviewImageError"
                />
                <div class="preview-actions">
                  <el-button 
                    type="danger" 
                    size="small" 
                    :icon="Delete"
                    @click="handleRemoveCoverImage"
                  >
                    移除封面
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-card>

      <el-card title="其他设置">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预计时长">
              <el-input-number
                v-model="form.duration"
                :min="1"
                :max="999"
                placeholder="分钟"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序">
              <el-input-number
                v-model="form.sortOrder"
                :min="0"
                :max="999"
                placeholder="排序"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="课程标签">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            placeholder="请选择或创建标签"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发布状态">
              <el-switch
                v-model="form.isPublished"
                active-text="已发布"
                inactive-text="草稿"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐课程">
              <el-switch
                v-model="form.isFeatured"
                active-text="推荐"
                inactive-text="普通"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <!-- 图片选择器 -->
    <ImageSelector
      v-model="showImageSelector"
      @select="handleImageSelect"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Delete } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import ImageUpload from '@/components/ImageUpload.vue'
import ImageSelector from '@/components/ImageSelector.vue'
import { getImagePreviewUrl } from '@/utils/upload'
import type { UploadFile } from '@/types/admin'

const route = useRoute()
const router = useRouter()

const formRef = ref<FormInstance>()
const isSaving = ref(false)
const showImageSelector = ref(false)

const isEdit = computed(() => !!route.params.id)

const categories = ref([
  { id: 1, name: '前端开发' },
  { id: 2, name: 'JavaScript' },
  { id: 3, name: 'Vue.js' }
])

const availableTags = ref(['基础', 'JavaScript', '前端', 'Vue', 'TypeScript'])

const form = reactive({
  title: '',
  slug: '',
  categoryId: null as number | null,
  difficulty: 'beginner',
  excerpt: '',
  content: '',
  coverImage: '',
  duration: 60,
  sortOrder: 0,
  tags: [] as string[],
  isPublished: false,
  isFeatured: false
})

const rules: FormRules = {
  title: [
    { required: true, message: '请输入课程标题', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入课程标识', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择课程分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入课程内容', trigger: 'blur' }
  ]
}

const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    isSaving.value = true
    
    // 模拟保存
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(isEdit.value ? '课程更新成功' : '课程创建成功')
    router.push('/admin/lessons')
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    isSaving.value = false
  }
}

// 处理封面图片上传成功
const handleCoverImageSuccess = (url: string) => {
  console.log('封面图片上传成功:', url)
  ElMessage.success('封面图片上传成功')
}

// 处理封面图片上传失败
const handleCoverImageError = (error: string) => {
  console.error('封面图片上传失败:', error)
  ElMessage.error(`封面图片上传失败: ${error}`)
}

// 处理封面图片移除
const handleCoverImageRemove = () => {
  form.coverImage = ''
  ElMessage.success('封面图片已移除')
}

// 处理从图库选择图片
const handleImageSelect = (image: UploadFile) => {
  form.coverImage = image.url
  ElMessage.success(`已选择图片: ${image.filename}`)
}

// 处理移除封面图片
const handleRemoveCoverImage = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要移除当前封面图片吗？',
      '移除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    form.coverImage = ''
    ElMessage.success('封面图片已移除')
  } catch {
    // 用户取消
  }
}

// 处理预览图片加载错误
const handlePreviewImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/placeholder-image.png' // 设置默认占位图
  console.warn('封面图片加载失败:', form.coverImage)
}

onMounted(() => {
  if (isEdit.value) {
    // 模拟加载课程数据
    Object.assign(form, {
      title: 'Vue 3 基础入门',
      slug: 'vue3-basics',
      categoryId: 3,
      difficulty: 'beginner',
      excerpt: '学习 Vue 3 的基础知识',
      content: '# Vue 3 基础入门\n\n这是一个关于 Vue 3 的基础教程...',
      coverImage: '/uploads/images/sample-cover.jpg',
      duration: 120,
      sortOrder: 1,
      tags: ['Vue', '基础'],
      isPublished: true,
      isFeatured: false
    })
  }
})
</script>

<style scoped>
.lesson-form-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.lesson-form .el-card {
  margin-bottom: 20px;
}

.content-card :deep(.el-card__body) {
  padding: 20px;
}

.cover-upload-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.upload-options {
  display: flex;
  align-items: center;
  gap: 20px;
}

.upload-divider {
  color: #909399;
  font-size: 14px;
  padding: 0 10px;
}

.current-cover-preview {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
}

.preview-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
  font-weight: 500;
}

.preview-image-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.preview-image {
  width: 200px;
  height: 120px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
}

.preview-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 响应式 */
@media (max-width: 768px) {
  .upload-options {
    flex-direction: column;
    align-items: stretch;
  }
  
  .upload-divider {
    text-align: center;
    padding: 10px 0;
  }
  
  .preview-image-wrapper {
    flex-direction: column;
  }
  
  .preview-image {
    width: 100%;
    max-width: 300px;
  }
}
</style> 